import BaseControl from "./BaseControl";
import MapCommon from "../../common/MapCommon";
import * as turf from '@turf/turf'
import mapboxgl from 'mapbox-gl';

export default class DrawAreaControl extends BaseControl {


  constructor(callBack,cancelCallback,errBack) {
    super(callBack,cancelCallback, errBack);
    this.points = [];//当前绘制点
    this.pointsRedo = [];//已撤销的点
    this.currentPoint = null;//鼠标当前点

    this.sourceId = "drawAreaControl";
    this.lineId = "drawAreaControlLine";
    this.pointId = "drawAreaPointLayer";
  }


  onAdd(map) {
    super.onAdd(map);
    this._ul = this._createUi();
    this._addDrawLayer();
    this._initMapEvent();
    return this._ul
  }

  _initMapEvent() {
    this._clickEvent = (e) => {
      this.points.push([e.lngLat.lng, e.lngLat.lat])
      this._update();
      this._preventDefault(e);
    };
    this.map.on("click", this._clickEvent);
    this._dbClickEvent = (e) => {
      if(this.points.length>=3){
        this.finish();
      }
      this._preventDefault(e);
    };
    this._rightClickEvent = (e) => {
      if(this.points.length>3){
        this.finish();
      }
      this._preventDefault(e);
    };
    this.map.on("dblclick", this._dbClickEvent);

    this.map.on("contextmenu", this._rightClickEvent);
    this._moveEvent = (e) => {
      this.currentPoint = [e.lngLat.lng, e.lngLat.lat];
      this._update();
      this._preventDefault(e)
    };
    this.map.on("mousemove", this._moveEvent);
    //关闭双击缩放d
    this._doubleClickZoom=this.map.doubleClickZoom.isEnabled()
    if(this._doubleClickZoom){
      this.map.doubleClickZoom.disable();
    }
  }
  /**
   * 移除长度文字
   */
  clearPopup(){
    if(this.popup){
      this.popup.remove();
      this.popup=null;
    }
  }
  updateArea(feature){
    this.clearPopup();
    let area=turf.area(feature);
    let center=turf.center(feature);

    this.popup = new mapboxgl.Popup({
      closeButton: false,
      closeOnClick:false,
      className:this.popupClassName
    });
    this.popup.setLngLat(center.geometry.coordinates)
      .setText((area*0.0015).toFixed(2)+"亩")
      .addTo(this.map);
  }
  _closeMapEvent() {
    if (this._clickEvent) {
      this.map.off("click", this._clickEvent);
      this._clickEvent = undefined
    }
    if (this._moveEvent) {
      this.map.off("mousemove", this._moveEvent);
      this._moveEvent = undefined
    }
    if (this._dbClickEvent) {
      this.map.off("dblclick", this._dbClickEvent);
      this._dbClickEvent = undefined
    }
    if (this._rightClickEvent) {
      this.map.off("contextmenu", this._rightClickEvent);
      this._rightClickEvent = undefined
    }
  }

  _createUi() {
    //改变鼠标形状
    this._defaultCursor=this.map.getCanvas().style.cursor;
    this.map.getCanvas().style.cursor="crosshair";
    this._defaultContextmenu=this.map.getCanvas().oncontextmenu;
    this.map.getCanvas().oncontextmenu = function (event) {
      event.preventDefault();
    };

    let ul = document.createElement("ul");
    ul.className = "mapboxgl-ctrl-drawArea mapboxgl-ctrl";
    ul.addEventListener("contextmenu", this._preventDefault);
    let liCancle = this._createLi("取消", "iconfont icon-quxiao");
    ul.appendChild(liCancle);
    liCancle.addEventListener("click", () => {
      this.onRemove();
      this.cancel();
    })
    this.liUndo = this._createLi("撤销", "iconfont icon-chehui");
    this.liUndo.setAttribute("disabled",true);
    this.liUndo.addEventListener("click", () => {
      this._undo()
    })
    ul.appendChild(this.liUndo);
    this.liRedo = this._createLi("重做", "iconfont icon-zhongzuo");
    this.liRedo.setAttribute("disabled",true);
    ul.appendChild(this.liRedo);
    this.liRedo.addEventListener("click", () => {
      this._redo()
    })
    this.liFinish = this._createLi("完成", "iconfont icon-wanchengchenggong");
    this.liFinish.setAttribute("disabled",true);
    ul.appendChild(this.liFinish);
    this.liFinish.addEventListener("click", () => {
      this.finish()
    })

    return ul;
  }
  finish(){
    this.onRemove();
    if(this.points.length<=3){
      return null
    }
    this.points.push(this.points[0]);
    super.finish({
      type: "FeatureCollection",
      features: [
        {
          type: "Feature",
          properties: {},
          geometry: {
            type: "Polygon",
            coordinates: [this.points],
          },
        },
      ],
    })
  }
  /**
   * 重做
   * @private
   */
  _redo() {
    if (this.pointsRedo.length === 0) {
      return
    }
    this.points.push(this.pointsRedo[this.pointsRedo.length - 1]);
    this.pointsRedo.splice(this.pointsRedo.length - 1, 1);
    this._update();
  }

  /**
   * 撤销
   * @private
   */
  _undo() {
    if (this.points.length === 0) {
      return
    }
    this.pointsRedo.push(this.points[this.points.length - 1]);
    this.points.splice(this.points.length - 1, 1);
    this._update();
  }

  /**
   * 移除绘制图层
   * @private
   */
  _removeDrawLayer() {
    MapCommon.removeLayer(this.map, this.sourceId);
    MapCommon.removeLayer(this.map, this.lineId);
    MapCommon.removeLayer(this.map, this.pointId);
    MapCommon.removeSource(this.map, this.sourceId);
    MapCommon.removeSource(this.map, this.lineId);
    MapCommon.removeSource(this.map, this.pointId);
  }

  /**
   * 绘制节点
   * @private
   */
 _addPoints(){
    let featureCollection = {
      type: "FeatureCollection",
      features: []
    };
    for (let i = 0; i < this.points.length; i++) {
      featureCollection.features.push({
        type: "Feature",
        properties: {
          index:i
        },
        geometry: {
          type: "Point",
          coordinates: this.points[i]
        }
      })
    }
    if(this.map.getSource(this.pointId)){
      this.map.getSource(this.pointId).setData(featureCollection);
    }else {
      this.map.addSource(this.pointId, {
        "type": "geojson",
        "data": featureCollection
      });
    }
    if(!this.map.getLayer(this.pointId)){
      this.map.addLayer({
        id: this.pointId,
        type: "circle",
        source: this.pointId,
        layout: {visibility:"visible"},
        paint: {
          "circle-color": "#0FF",
          "circle-radius": 4,
          "circle-stroke-width":2,
          "circle-stroke-color":"#FFF"
        },
      });
    }
 }
  //添加绘制图层
  _addDrawLayer() {
    let geoJson = {
      type: "FeatureCollection",
      features: [
        {
          type: "Feature",
          properties: {},
          geometry: {
            type: "Polygon",
            coordinates: [],
          },
        },
      ],
    };
    if (!this.map.getSource(this.sourceId)) {
      this.map.addSource(this.sourceId, {
        type: "geojson",
        data: geoJson,
      });
    }
    let geoJsonLine = {
      type: "FeatureCollection",
      features: [
        {
          type: "Feature",
          properties: {},
          geometry: {
            type: "Polygon",
            coordinates: [],
          },
        },
      ],
    };
    if (!this.map.getSource(this.lineId)) {
      this.map.addSource(this.lineId, {
        type: "geojson",
        data: geoJsonLine,
      });
    }

    if (!this.map.getLayer(this.sourceId)) {
      this.map.addLayer({
        id: this.sourceId,
        type: "fill",
        source: this.sourceId,
        layout: {},
        paint: {
          'fill-color': '#fbb03b',
          'fill-outline-color': '#fbb03b',
          'fill-opacity': 0.1
        },
      });
    }
    if (!this.map.getLayer(this.lineId)) {
      this.map.addLayer({
        id: this.lineId,
        type: "line",
        source: this.lineId,
        layout: {},
        paint: {
          'line-color': '#fbb03b',
          'line-dasharray': [1, 1],
          'line-width': 2
        }
      });
    }
  }

  /**
   * 更新绘制效果
   * @private
   */
  _update() {
    //更改按钮状态
    this.liFinish.setAttribute("disabled",this.points.length <= 3);
    this.liUndo.setAttribute("disabled",this.points.length <= 0);
    this.liRedo.setAttribute("disabled",this.pointsRedo.length <= 0);
    this._addPoints();


    let coordinates = [].concat(this.points);
    coordinates.push(this.currentPoint);
    coordinates.push(coordinates[0]);
    this.map.getSource(this.sourceId).setData({
      type: "FeatureCollection",
      features: [
        {
          type: "Feature",
          properties: {},
          geometry: {
            type: "Polygon",
            coordinates: [coordinates],
          },
        },
      ],
    });
    if(coordinates.length>3){
      this.updateArea({
        type: "FeatureCollection",
        features: [
          {
            type: "Feature",
            properties: {},
            geometry: {
              type: "Polygon",
              coordinates: [coordinates],
            },
          },
        ],
      })
    }
    this.map.getSource(this.lineId).setData({
          type: "Feature",
          properties: {},
          geometry: {
            type: "Polygon",
            coordinates: [coordinates],
          },
        }
    );

  }

  /**
   * 产生li标签
   * @private
   */
  _createLi(text, className) {
    let li = document.createElement("li");
    let span = document.createElement("span");
    span.className = className;
    li.appendChild(span);
    let div = document.createElement("div");
    div.innerText = text;
    li.appendChild(div);
    return li;
  }

  onRemove() {
    super.onRemove();
    this.map.getCanvas().style.cursor=this._defaultCursor;
    //启用双击缩放
   if(this._doubleClickZoom){
     this.map.doubleClickZoom.enable()
   }
   //恢复地图右键事件
    this.map.getCanvas().oncontextmenu=this._defaultContextmenu;
    if (!this._ul) {
      return
    }

    this._ul.parentNode.removeChild(this._ul);

    this._closeMapEvent();
    this._removeDrawLayer();
    this.clearPopup()
  }


}
